package com.yjhb.android.sbz.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.Shape;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 创建者 zx
 * 创建时间 2020/10/10 14:26
 */
public class CircularProgressBar extends FrameLayout {
    private static final String TAG = "CircularProgressBar";

    private Paint paint;
    private int circularWidth = 10;
    private int circularColor = Color.parseColor("#FFC235");
    private float progress = 0.0f; //进度
    ShapeDrawable drawable;
    private int bgColor = Color.parseColor("#55000000");

    public CircularProgressBar(@NonNull Context context) {
        this(context, null);
    }

    public CircularProgressBar(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircularProgressBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setStrokeWidth(circularWidth);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(circularColor);
        paint.setAntiAlias(true);
        drawable = new ShapeDrawable();
        drawable.setShape(new Shape() {
            @Override
            public void draw(Canvas canvas, Paint paint) {
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(bgColor);
                canvas.drawCircle(getWidth()/2,getHeight()/2,getWidth()/2,paint);
            }
        });
        setBackground(drawable);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        drawCircular(canvas);
    }


    private void drawCircular(Canvas canvas) {
        canvas.save();
        canvas.rotate(-90f,getWidth()/2,getHeight()/2);
        canvas.drawArc(circularWidth/2, circularWidth/2, getWidth() - circularWidth/2, getHeight() - circularWidth/2,
                 0f,progress * 360f, false, paint);
        canvas.restore();
    }

    /**
     * 更新进度
     * @param progress 当前进度  范围为0~1f
     */
    public void updateProgress(float progress){
        this.progress = progress;
        invalidate();
    }
}
